package com.gxuwz.weather;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.TextView;
import android.view.MotionEvent;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import android.view.WindowManager;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.gxuwz.weather.R;
import com.gxuwz.weather.api.RealTimeRequest;
import com.gxuwz.weather.adapter.CityListAdapter;
import com.gxuwz.weather.fragment.WeatherFragment;
import com.gxuwz.weather.model.CityWeatherDisplayItem;
import com.gxuwz.weather.db.CityDao;
import com.gxuwz.weather.model.CityInfo;
import com.gxuwz.weather.db.CityDatabaseHelper;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections; // 用于同步列表
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CityManageActivity extends AppCompatActivity {

    private static final String PREF_CITY_LIST = "city_list";

    private SearchView searchView;
    private RecyclerView rvCities;
    private CityListAdapter cityListAdapter;
    private List<String> savedCityNames; // 存储仅城市名称，用于SharedPreferences
    private List<CityWeatherDisplayItem> displayCityWeatherList; // 存储用于UI显示的数据
    private SharedPreferences sharedPreferences;

    // 搜索结果相关UI
    private LinearLayout llSearchResultContainer;
    private TextView tvSearchResultCityName;
    private TextView tvSearchResultTemperature;
    private TextView tvSearchResultWeather;
    private TextView tvSearchResultHighLow;
    private TextView tvSearchResultWind;
    private TextView tvSearchResultHumidity;
    private ImageView ivAddCityButton;
    private TextView tvCancelButton; // 取消按钮

    private CityDao cityDao;

    // 新增：模糊搜索点击监听接口
    public interface OnSearchItemClickListener { 
        void onItemClick(CityInfo item); 
    }

    // 新增：模糊搜索结果相关
    private RecyclerView rvSearchResultList;
    private SearchResultAdapter searchResultAdapter;
    private List<CityInfo> fuzzySearchResultList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_manage);

        // 初始化数据库
        cityDao = new CityDao(this);
        cityDao.open();

        // 新增：导入all_cities.csv数据（如果表为空）
        importAllCitiesIfNeeded();

        // 加载已保存的城市列表
        loadSavedCityNames();

        searchView = findViewById(R.id.search_view);
        tvCancelButton = findViewById(R.id.tv_cancel_button); // 初始化取消按钮

        // 获取搜索框中的 EditText，并设置文本颜色和提示文本颜色为白色
        int searchTextId = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        EditText searchEditText = searchView.findViewById(searchTextId);
        if (searchEditText != null) {
            searchEditText.setTextColor(Color.WHITE);
            searchEditText.setHintTextColor(Color.WHITE);

            // 为搜索框的EditText设置焦点监听器
            searchEditText.setOnFocusChangeListener((v, hasFocus) -> {
                if (hasFocus) {
                    tvCancelButton.setVisibility(View.VISIBLE); // 获得焦点时显示取消按钮
                } else {
                    tvCancelButton.setVisibility(View.GONE); // 失去焦点时隐藏取消按钮
                }
            });
        }

// 获取搜索框的放大镜图标，并设置其颜色为白色
        int searchMagIconId = searchView.getContext().getResources().getIdentifier("android:id/search_mag_icon", null, null);
        ImageView searchMagIcon = searchView.findViewById(searchMagIconId);
        if (searchMagIcon != null) {
            searchMagIcon.setColorFilter(Color.WHITE);
        }


        rvCities = findViewById(R.id.rv_cities);
        llSearchResultContainer = findViewById(R.id.ll_search_result_container);
        tvSearchResultCityName = findViewById(R.id.tv_search_result_city_name);
        tvSearchResultTemperature = findViewById(R.id.tv_search_result_temperature);
        tvSearchResultWeather = findViewById(R.id.tv_search_result_weather);
        tvSearchResultHighLow = findViewById(R.id.tv_search_result_high_low);
        tvSearchResultWind = findViewById(R.id.tv_search_result_wind);
        tvSearchResultHumidity = findViewById(R.id.tv_search_result_humidity);
        ivAddCityButton = findViewById(R.id.iv_add_city_button);

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        loadSavedCityNames(); // 加载已保存的城市名称列表

        displayCityWeatherList = Collections.synchronizedList(new ArrayList<>()); // 初始化同步列表
        // 初始化 RecyclerView，使用空的 displayCityWeatherList
        rvCities.setLayoutManager(new LinearLayoutManager(this));
        cityListAdapter = new CityListAdapter(displayCityWeatherList,
                item -> {
                    Intent intent = new Intent(CityManageActivity.this, MainActivity.class);
                    intent.putExtra("selected_city", item.getCityName());
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                },
                (item, position) -> {
                    removeCity(item.getCityName(), position);
                }
        );
        rvCities.setAdapter(cityListAdapter);

        // 加载并显示所有已保存城市的天气数据
        fetchAndDisplayAllSavedCitiesWeather();

        // 新增：初始化模糊搜索结果RecyclerView
        rvSearchResultList = findViewById(R.id.rv_search_result_list);
        searchResultAdapter = new SearchResultAdapter(fuzzySearchResultList, item -> {
            // 点击某个城市后，弹出全屏天气详情弹窗
            CityWeatherDetailDialogFragment dialog = CityWeatherDetailDialogFragment.newInstance(item.getAreaCn());
            dialog.show(getSupportFragmentManager(), "city_weather_detail");
        });
        rvSearchResultList.setLayoutManager(new LinearLayoutManager(this));
        rvSearchResultList.setAdapter(searchResultAdapter);
        rvSearchResultList.setVisibility(View.GONE);

        // 修改搜索框监听，支持模糊查询
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 选中后隐藏下拉列表，显示天气详情
                rvSearchResultList.setVisibility(View.GONE);
                performCitySearch(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.isEmpty()) {
                    rvSearchResultList.setVisibility(View.GONE);
                    llSearchResultContainer.setVisibility(View.GONE);
                    return false;
                }
                // 模糊查询
                Log.d("CityManageActivity", "开始模糊查询: " + newText);
                List<CityInfo> result = cityDao.searchCities(newText);
                Log.d("CityManageActivity", "查询结果数量: " + result.size());
                fuzzySearchResultList.clear();
                fuzzySearchResultList.addAll(result);
                searchResultAdapter.notifyDataSetChanged();
                rvSearchResultList.setVisibility(result.isEmpty() ? View.GONE : View.VISIBLE);
                llSearchResultContainer.setVisibility(View.GONE);
                return false;
            }
        });

        // 取消按钮点击事件
        tvCancelButton.setOnClickListener(v -> {
            searchView.setQuery("", false); // 清空搜索框内容
            searchView.clearFocus(); // 移除搜索框焦点
            llSearchResultContainer.setVisibility(View.GONE); // 隐藏搜索结果
            tvCancelButton.setVisibility(View.GONE); // 隐藏取消按钮
            // 隐藏软键盘
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        });

        // 添加城市按钮点击事件
        ivAddCityButton.setOnClickListener(v -> {
            String cityToAdd = tvSearchResultCityName.getText().toString();
            if (!cityToAdd.isEmpty() && !savedCityNames.contains(cityToAdd)) {
                addCity(cityToAdd);
                llSearchResultContainer.setVisibility(View.GONE);
                searchView.setQuery("", false);
            } else if (savedCityNames.contains(cityToAdd)) {
                Toast.makeText(CityManageActivity.this, "该城市已在列表中", Toast.LENGTH_SHORT).show();
            }
        });

        // 实现左滑删除功能
        ItemTouchHelper.Callback itemTouchHelperCallback = new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                // 只允许向左滑动
                return makeMovementFlags(0, ItemTouchHelper.LEFT);
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    CityWeatherDisplayItem item = displayCityWeatherList.get(position);
                    removeCity(item.getCityName(), position);
                }
            }

            @Override
            public float getSwipeThreshold(@NonNull RecyclerView.ViewHolder viewHolder) {
                // 返回0.3f，表示滑动超过30%时触发删除
                return 0.3f;
            }

            @Override
            public float getSwipeEscapeVelocity(float defaultValue) {
                // 返回一个较大的值，防止快速滑动导致意外触发
                return defaultValue * 2;
            }

            @Override
            public float getSwipeVelocityThreshold(float defaultValue) {
                // 返回一个较大的值，防止快速滑动导致意外触发
                return defaultValue * 2;
            }
        };

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemTouchHelperCallback);
        itemTouchHelper.attachToRecyclerView(rvCities);

        cityListAdapter.setOnSetHomeListener(cityName -> {
            sharedPreferences.edit().putString("home_city", cityName).apply();
            cityListAdapter.notifyDataSetChanged();
            Toast.makeText(this, "已设置常驻地：" + cityName, Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (cityDao != null) {
            cityDao.close();
        }
    }

    private void loadSavedCityNames() {
        savedCityNames = cityDao.getAllCities();
        if (savedCityNames == null) {
            savedCityNames = new ArrayList<>();
        }
    }

    /**
     * 获取并显示所有已保存城市的天气数据
     */
    private void fetchAndDisplayAllSavedCitiesWeather() {
        // 清空显示列表
        displayCityWeatherList.clear();
        // 通知适配器数据已清空
        cityListAdapter.setCityList(displayCityWeatherList);

        // 获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
        String currentTime = sdf.format(new Date());

        // 先请求定位城市天气
        String gpsCity = PreferenceManager.getDefaultSharedPreferences(this).getString("gps_city", "");
        if (gpsCity != null && !gpsCity.isEmpty()) {
            RealTimeRequest.getWeather(gpsCity, new RealTimeRequest.WeatherCallback() {
                @Override
                public void onSuccess(String temperature, String weather, String windDirection, String windSpeed, String aqi,
                                      String sunrise, String sunset, JsonArray hourlyData, JsonObject now, JsonObject day, JsonObject night, JsonObject data,JsonObject lifeIndex) {
                    runOnUiThread(() -> {
                        if (now != null && now.has("cityname") && now.has("temp") && now.has("weather")) {
                            String fetchedCityName = now.get("cityname").getAsString();
                            String currentTemp = now.get("temp").getAsString() + "°";
                            String weatherCondition = now.get("weather").getAsString();

                            String highTemp = day.has("temperature") ? "最高 " + day.get("temperature").getAsString() + "°" : "";
                            String lowTemp = night.has("temperature") ? "最低 " + night.get("temperature").getAsString() + "°" : "";

                            String alertMessage = null;
                            JsonArray alarmList = data.has("alarmList") ? data.getAsJsonArray("alarmList") : null;
                            if (alarmList != null && alarmList.size() > 0) {
                                JsonObject firstAlarm = alarmList.get(0).getAsJsonObject();
                                if (firstAlarm.has("signalType")) {
                                    alertMessage = firstAlarm.get("signalType").getAsString() + "及其他" + (alarmList.size() - 1 > 0 ? alarmList.size() - 1 + "则" : "");
                                }
                            }

                            boolean isMyCurrentLocation = true;
                            CityWeatherDisplayItem newItem = new CityWeatherDisplayItem(
                                    fetchedCityName,
                                    currentTemp,
                                    weatherCondition,
                                    highTemp,
                                    lowTemp,
                                    currentTime,
                                    alertMessage,
                                    isMyCurrentLocation
                            );
                            // 插入到第一个
                            displayCityWeatherList.add(0, newItem);
                            cityListAdapter.setCityList(displayCityWeatherList);
                        }
                    });
                }
                @Override
                public void onError(String error) {
                    runOnUiThread(() -> {
                        CityWeatherDisplayItem errorItem = new CityWeatherDisplayItem(
                                gpsCity, "N/A", "获取失败", "", "", currentTime, null, true
                        );
                        displayCityWeatherList.add(0, errorItem);
                        cityListAdapter.setCityList(displayCityWeatherList);
                    });
                }
            });
        }

        // 如果没有保存的城市，直接返回
        if (savedCityNames == null || savedCityNames.isEmpty()) {
            return;
        }

        // 为每个数据库城市发起天气请求
        for (String cityName : savedCityNames) {
            // 跳过定位城市，避免重复
            if (cityName.equals(gpsCity)) continue;
            RealTimeRequest.getWeather(cityName, new RealTimeRequest.WeatherCallback() {
                @Override
                public void onSuccess(String temperature, String weather, String windDirection, String windSpeed, String aqi,
                                      String sunrise, String sunset, JsonArray hourlyData, JsonObject now, JsonObject day, JsonObject night, JsonObject data,JsonObject lifeIndex) {
                    runOnUiThread(() -> {
                        if (now != null && now.has("cityname") && now.has("temp") && now.has("weather")) {
                            String fetchedCityName = now.get("cityname").getAsString();
                            String currentTemp = now.get("temp").getAsString() + "°";
                            String weatherCondition = now.get("weather").getAsString();

                            String highTemp = day.has("temperature") ? "最高 " + day.get("temperature").getAsString() + "°" : "";
                            String lowTemp = night.has("temperature") ? "最低 " + night.get("temperature").getAsString() + "°" : "";

                            String alertMessage = null;
                            JsonArray alarmList = data.has("alarmList") ? data.getAsJsonArray("alarmList") : null;
                            if (alarmList != null && alarmList.size() > 0) {
                                JsonObject firstAlarm = alarmList.get(0).getAsJsonObject();
                                if (firstAlarm.has("signalType")) {
                                    alertMessage = firstAlarm.get("signalType").getAsString() + "及其他" + (alarmList.size() - 1 > 0 ? alarmList.size() - 1 + "则" : "");
                                }
                            }

                            boolean isMyCurrentLocation = false;
                            CityWeatherDisplayItem newItem = new CityWeatherDisplayItem(
                                    fetchedCityName,
                                    currentTemp,
                                    weatherCondition,
                                    highTemp,
                                    lowTemp,
                                    currentTime,
                                    alertMessage,
                                    isMyCurrentLocation
                            );

                            // 查找并替换现有项，如果不存在则添加
                            boolean found = false;
                            for (int i = 0; i < displayCityWeatherList.size(); i++) {
                                if (displayCityWeatherList.get(i).getCityName().equals(newItem.getCityName())) {
                                    displayCityWeatherList.set(i, newItem);
                                    found = true;
                                    break;
                                }
                            }
                            if (!found) {
                                displayCityWeatherList.add(newItem);
                            }

                            // 按照保存的城市名称顺序进行排序，定位城市始终第一个
                            String gpsCity1 = PreferenceManager.getDefaultSharedPreferences(CityManageActivity.this).getString("gps_city", "");
                            Collections.sort(displayCityWeatherList, (o1, o2) -> {
                                if (o1.isMyCurrentLocation()) return -1;
                                if (o2.isMyCurrentLocation()) return 1;
                                int index1 = savedCityNames.indexOf(o1.getCityName());
                                int index2 = savedCityNames.indexOf(o2.getCityName());
                                return Integer.compare(index1, index2);
                            });

                            // 更新适配器
                            cityListAdapter.setCityList(displayCityWeatherList);
                        }
                    });
                }
                @Override
                public void onError(String error) {
                    runOnUiThread(() -> {
                        CityWeatherDisplayItem errorItem = new CityWeatherDisplayItem(
                                cityName, "N/A", "获取失败", "", "", currentTime, null, false
                        );
                        displayCityWeatherList.add(errorItem);
                        cityListAdapter.setCityList(displayCityWeatherList);
                    });
                }
            });
        }
    }


    /**
     * 执行城市搜索 (只搜索一个城市并显示结果)
     * @param query 搜索查询 (地名、地区代码、经/纬度)
     */
    private void performCitySearch(String query) {
        if (query.isEmpty()) {
            Toast.makeText(this, "请输入搜索内容", Toast.LENGTH_SHORT).show();
            llSearchResultContainer.setVisibility(View.GONE);
            return;
        }

        RealTimeRequest.getWeather(query, new RealTimeRequest.WeatherCallback() {
            @Override
            public void onSuccess(String temperature, String weather, String windDirection, String windSpeed, String aqi,
                                  String sunrise, String sunset, JsonArray hourlyData, JsonObject now, JsonObject day, JsonObject night, JsonObject data, JsonObject lifeIndex) {
                runOnUiThread(() -> {
                    if (now != null && now.has("cityname") && now.has("temp") && now.has("weather")) {
                        String cityName = now.get("cityname").getAsString();
                        String temp = now.get("temp").getAsString();
                        String weatherCondition = now.get("weather").getAsString();
                        
                        // 获取最高最低温度
                        String highTemp = day.has("temperature") ? day.get("temperature").getAsString() : "";
                        String lowTemp = night.has("temperature") ? night.get("temperature").getAsString() : "";
                        
                        // 获取风向和风速
                        String windInfo = windDirection + "风 " + windSpeed + "级";
                        
                        // 获取湿度
                        String humidity = lifeIndex != null && lifeIndex.has("SD") ?
                            lifeIndex.getAsJsonObject("SD").get("value").getAsString() + "%" : "暂无数据";

                        // 更新UI
                        tvSearchResultCityName.setText(cityName);
                        tvSearchResultTemperature.setText(temp + "°");
                        tvSearchResultWeather.setText(weatherCondition);
                        tvSearchResultHighLow.setText(String.format("最高 %s° 最低 %s°", highTemp, lowTemp));
                        tvSearchResultWind.setText(windInfo);
                        tvSearchResultHumidity.setText("湿度 " + humidity);
                        
                        // 根据天气设置背景
                        if (weatherCondition.contains("晴")) {
                            llSearchResultContainer.setBackgroundResource(R.drawable.bg_sum_72);
                        } else if (weatherCondition.contains("云")) {
                            llSearchResultContainer.setBackgroundResource(R.drawable.bg_duoyun_72);
                        } else if (weatherCondition.contains("雨")) {
                            llSearchResultContainer.setBackgroundResource(R.drawable.bg_rain_72);
                        } else if (weatherCondition.contains("阴")) {
                            llSearchResultContainer.setBackgroundResource(R.drawable.bg_yintian_72);
                        }
                        else if (weatherCondition.contains("雾")) {
                            llSearchResultContainer.setBackgroundResource(R.drawable.bg_yintian_72);
                        }

                        llSearchResultContainer.setVisibility(View.VISIBLE);

                        if (savedCityNames.contains(cityName)) {
                            ivAddCityButton.setVisibility(View.GONE);
                            Toast.makeText(CityManageActivity.this, "该城市已在列表中", Toast.LENGTH_SHORT).show();
                        } else {
                            ivAddCityButton.setVisibility(View.VISIBLE);
                        }
                    } else {
                        Toast.makeText(CityManageActivity.this, "未能获取到该城市的天气数据", Toast.LENGTH_SHORT).show();
                        llSearchResultContainer.setVisibility(View.GONE);
                    }
                });
            }

            @Override
            public void onError(String error) {
                runOnUiThread(() -> {
                    Toast.makeText(CityManageActivity.this, "搜索失败: " + error, Toast.LENGTH_LONG).show();
                    llSearchResultContainer.setVisibility(View.GONE);
                });
            }
        });
    }

    private void addCity(String cityToAdd) {
        if (!savedCityNames.contains(cityToAdd)) {
            // 保存到数据库
            long result = cityDao.insertCity(cityToAdd);
            if (result != -1) {
                savedCityNames.add(cityToAdd);
                // 重新获取并显示所有城市的天气数据，包括新添加的城市
                fetchAndDisplayAllSavedCitiesWeather();
                Toast.makeText(this, "城市添加成功: " + cityToAdd, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "城市添加失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "该城市已在列表中", Toast.LENGTH_SHORT).show();
        }
    }

    private void removeCity(String cityToRemove, int position) {
        // 禁止删除定位城市
        CityWeatherDisplayItem item = displayCityWeatherList.get(position);
        if (item.isMyCurrentLocation()) {
            Toast.makeText(this, "定位城市不能删除", Toast.LENGTH_SHORT).show();
            cityListAdapter.notifyItemChanged(position); // 恢复滑动删除的UI
            return;
        }
        Log.d("CityManageActivity", "开始删除城市: " + cityToRemove + ", 位置: " + position);
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("删除城市")
                .setMessage("确定要删除 " + cityToRemove + " 吗？")
                .setPositiveButton("删除", (dialog1, which) -> {
                    Log.d("CityManageActivity", "确认删除城市: " + cityToRemove);
                    // 从数据库中删除
                    int result = cityDao.deleteCity(cityToRemove);
                    if (result > 0) {
                        // 从保存的城市列表中移除
                        if (savedCityNames.remove(cityToRemove)) {
                            // 从显示列表中移除
                            if (position >= 0 && position < displayCityWeatherList.size()) {
                                displayCityWeatherList.remove(position);
                                cityListAdapter.notifyItemRemoved(position);
                                cityListAdapter.notifyItemRangeChanged(position, displayCityWeatherList.size());
                            }
                            // 重新获取并显示所有城市的天气数据
                            fetchAndDisplayAllSavedCitiesWeather();
                            Toast.makeText(CityManageActivity.this, "城市已删除: " + cityToRemove, Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Log.e("CityManageActivity", "从数据库中删除城市失败: " + cityToRemove);
                        Toast.makeText(CityManageActivity.this, "删除城市失败", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", (dialog12, which) -> {
                    Log.d("CityManageActivity", "取消删除城市: " + cityToRemove);
                    // 恢复被滑掉的项
                    cityListAdapter.notifyItemChanged(position);
                    dialog12.dismiss();
                })
                .setCancelable(true)
                .create();

        // 设置圆角背景
        dialog.setOnShowListener(d -> {
            // 设置按钮颜色
            dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(0xFF2196F3); // #2196F3
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(0xFFFF0000); // red

            // 设置圆角背景
            dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_bg);
        });

        dialog.show();
    }

    // 新增：模糊搜索结果适配器
    class SearchResultAdapter extends RecyclerView.Adapter<SearchResultAdapter.ViewHolder> {
        private List<CityInfo> data;
        private OnSearchItemClickListener listener;
        public SearchResultAdapter(List<CityInfo> data, OnSearchItemClickListener listener) {
            this.data = data;
            this.listener = listener;
        }
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_search_city, parent, false);
            return new ViewHolder(view);
        }
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            CityInfo item = data.get(position);
            // 高亮关键词
            String cityName = item.getAreaCn();
            String keyword = "";
            if (!fuzzySearchResultList.isEmpty() && !searchView.getQuery().toString().isEmpty()) {
                keyword = searchView.getQuery().toString();
            }
            if (!keyword.isEmpty() && cityName.contains(keyword)) {
                int start = cityName.indexOf(keyword);
                int end = start + keyword.length();
                SpannableString spannable = new SpannableString(cityName);
                spannable.setSpan(new ForegroundColorSpan(0xFFFFFFFF), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannable.setSpan(new ForegroundColorSpan(0xFF5d5d61), 0, start, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                if (end < cityName.length()) {
                    spannable.setSpan(new ForegroundColorSpan(0xFF5d5d61), end, cityName.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                holder.tvCityName.setText(spannable);
            } else {
                holder.tvCityName.setText(cityName);
            }
            holder.tvAreaCode.setText(item.getAreaCode());
            holder.itemView.setOnClickListener(v -> listener.onItemClick(item));
        }
        @Override
        public int getItemCount() { return data.size(); }
        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvCityName, tvAreaCode;
            ViewHolder(@NonNull View itemView) {
                super(itemView);
                tvCityName = itemView.findViewById(R.id.tv_city_name);
                tvAreaCode = itemView.findViewById(R.id.tv_area_code);
            }
        }
    }

    /**
     * 如果all_cities表为空，则导入CSV数据
     */
    private void importAllCitiesIfNeeded() {
        try {
            Log.d("CityManageActivity", "开始检查all_cities表...");
            // 检查all_cities表是否为空
            List<CityInfo> existingCities = cityDao.searchCities("北京");
            Log.d("CityManageActivity", "现有城市数量: " + existingCities.size());
            
            // 强制导入数据（临时测试用）
            Log.d("CityManageActivity", "开始导入all_cities.csv数据...");
            CityDatabaseHelper dbHelper = new CityDatabaseHelper(this);
            dbHelper.importAllCitiesFromAssets(this);
            Log.d("CityManageActivity", "已导入all_cities.csv数据");
            
            // 再次检查导入结果
            List<CityInfo> afterImport = cityDao.searchCities("北京");
            Log.d("CityManageActivity", "导入后城市数量: " + afterImport.size());
            
            if (!afterImport.isEmpty()) {
                Log.d("CityManageActivity", "导入成功，示例城市: " + afterImport.get(0).getAreaCn());
            }
            
        } catch (Exception e) {
            Log.e("CityManageActivity", "导入城市数据失败", e);
            e.printStackTrace();
        }
    }

    // 新增：全屏天气详情弹窗
    public static class CityWeatherDetailDialogFragment extends DialogFragment {
        private String cityName;
        public static CityWeatherDetailDialogFragment newInstance(String cityName) {
            CityWeatherDetailDialogFragment fragment = new CityWeatherDetailDialogFragment();
            Bundle args = new Bundle();
            args.putString("city_name", cityName);
            fragment.setArguments(args);
            return fragment;
        }
        @Override
        public void onStart() {
            super.onStart();
            // 设置全屏
            if (getDialog() != null && getDialog().getWindow() != null) {
                getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
                getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            }
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.dialog_city_weather_detail, container, false);
            cityName = getArguments() != null ? getArguments().getString("city_name") : "";
            // 取消按钮
            view.findViewById(R.id.tv_cancel).setOnClickListener(v -> dismiss());
            // 添加按钮
            view.findViewById(R.id.tv_add).setOnClickListener(v -> {
                if (getActivity() instanceof CityManageActivity) {
                    ((CityManageActivity)getActivity()).addCity(cityName);
                }
                dismiss();
            });
            // 加载天气详情内容（复用WeatherFragment，isPreview=true）
            if (savedInstanceState == null) {
                getChildFragmentManager().beginTransaction()
                    .replace(R.id.weather_content_container, com.gxuwz.weather.fragment.WeatherFragment.newInstance(cityName, true))
                    .commit();
            }
            return view;
        }
    }

    // 新增：只展示天气的Fragment，不做数据库校验
    public static class CityWeatherDetailFragment extends androidx.fragment.app.Fragment {
        // ... 该类已不再需要，可保留但不再使用 ...
    }
}